<template>
	<div class="mt-4 relative">

		<div class="absolute right-0">
			<el-button v-if="info.device_type == 2" type="primary" @click="addChannel" v-prmis="'channel_add'">{{ $t('machine.channel.channelAdd')
			}}</el-button>
			<el-button type="primary" @click="getExport(1)" v-prmis="'channel_export'">{{
				$t('machine.channel.shelfExport') }}</el-button>
			<el-button type="primary" @click="getExport(2)" v-prmis="'channel_exportSku'">{{
				$t('machine.channel.skuExport') }}</el-button>
		</div>
		<div>
			<el-radio-group v-model="data.mactype" class="mb-4">
				<el-radio :label="1" size="large" border>{{ $t('machine.channel.basicUnit') }}</el-radio>
				<el-radio v-if="find.sub_cabinet !== 2" :label="2" size="large" border>{{ $t('machine.channel.expand') }}</el-radio>
			</el-radio-group>
		</div>

		<el-radio-group v-model="data.types" class="mb-4">
			<el-radio-button :label="1">{{ $t('machine.channel.inventory') }}</el-radio-button>
			<el-radio-button :label="2">{{ $t('machine.channel.price') }}</el-radio-button>
			<el-radio-button :label="3">{{ $t('machine.channel.pick') }}</el-radio-button>
			<el-radio-button :label="4">{{ $t('machine.channel.slot') }}</el-radio-button>
			<el-radio-button :label="5">{{ $t('machine.channel.channelStatus') }}</el-radio-button>
		</el-radio-group>

		<div v-for="(item, key) of data.list" class="mt-2 mb-6">
			<div :class="data.mactype == 1 ? 'w-full flex flex-wrap overflow-hidden' : 'w-full'">
				<div v-for="iem of item" :class="data.mactype == 1 ? '' : 'mb-4'">

					<div v-if="iem.channel_position == data.mactype"
						:class="iem.status == 3 ? 'border mx-2 relative rounded border-red-600' : 'border mx-2 relative rounded'"
						:style="'width: ' + iem.custom + 'px;height: 140px;'" @mouseenter="mousedown(iem)"
						@mouseleave="mouseleave(iem)">

						<div v-if="iem.isChannelinfo" class="delChannel"
							style="background-color: #5b5d6042;position: absolute;right: 0;left: 0;top: 0;bottom: 0;">
							<div style="margin:30px auto;width: 50px;">
								<el-button size="small" @click="channel_info(iem)">{{ $t('public.edit') }}</el-button>
								<el-button size="small" @click="delChannel(iem)" :disabled="info.device_type !== 2"
									:title="info.device_type !== 2 ? $t('machine.StoreType') : ''">{{ $t('public.del') }}</el-button>
							</div>
						</div>

						<div class="p-0.5 pl-1">{{ iem.channel_code }}</div>
						<div class="absolute top-0 right-0 p-0.5 text-base" @click="capture(iem.channel_code)"
							v-if="info.machine_level == 2">
							<el-icon>
								<Camera />
							</el-icon>
						</div>

						<div class="w-full h-2/3 flex justify-center" @click="channel_info(iem)">
							<img :src="iem.pic || product">
						</div>

						<div v-if="data.types == 1" class="p-0.5 pl-1">{{ iem.stock }}</div>
						<div v-if="data.types == 2" class="p-0.5 pl-1">{{ iem.retail_price }}</div>
						<div v-if="data.types == 3" class="p-0.5 pl-1">{{ getmode(iem.fetch_mode) }}</div>
						<div v-if="data.types == 4" class="p-0.5 pl-1">X{{ iem.slot_hole }}</div>
						<div v-if="data.types == 5" :class="iem.status == 2 ? 'p-0.5 pl-1 text-red-700' : 'p-0.5 pl-1'">
							{{ iem.status == 1 ? $t('public.normal') : iem.status == 2 ? $t('public.disable') : 'BAD' }}
						</div>

					</div>
				</div>
			</div>
		</div>
		<!-- 添加货道 -->
		<el-dialog v-model="addDialog" :title="$t('machine.channel.channelAdd')" center width="60%">
			<el-form v-if="addDialog" :model="data.addInfo" :rules="data.rules" :inline="true"
				class="grid gap-4 grid-cols-2 channel" :label-width="language == 'en' ? '165' : '120'">
				<el-form-item :label="$t('report.supplement.channelNum') + ':'" prop="channel_code" class="w-10/12">
					<el-input v-model="data.addInfo.channel_code" />
				</el-form-item>
				<el-form-item :label="$t('machine.goods.name') + ':'" prop="g_id" class="w-10/12">
					<el-select v-model="data.addInfo.g_id" @change="goodsChange"
						:style="data.addInfo.g_id ? 'width: 94%;' : ''" filterable>
						<el-option v-for="(item, key) in goodsList" :key="key" :label="item.g_id + '-' + item.g_name"
							:value="item.g_id" />
					</el-select>
					<el-icon v-if="data.addInfo.g_id" style="width: 6%;" size="20" @click="urlimg(data.addInfo.pic)">
						<Picture />
					</el-icon>
				</el-form-item>
				<el-form-item label="SKU:" prop="sku" class="w-10/12">
					<el-input v-model="data.addInfo.sku" disabled :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('eventlog.goods.barCode') + ':'" prop="bar_code" class="w-10/12">
					<el-input v-model="data.addInfo.bar_code" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.batch') + ':'" prop="batch_number" class="w-10/12">
					<el-input v-model="data.addInfo.batch_number" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.slot') + ':'" prop="slot_hole" class="w-10/12">
					<el-input v-model="data.addInfo.slot_hole" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.channelCap') + ':'" prop="capacity" class="w-10/12">
					<el-input-number v-model="data.addInfo.capacity" :min="0" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.sellInve') + ':'" prop="stock" class="w-10/12">
					<el-input-number v-model="data.addInfo.stock" :min="0" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.inventoryWarn') + ':'" prop="stock_warning" class="w-10/12">
					<el-input v-model.number="data.addInfo.stock_warning" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('date.saleTime') + ':'" prop="release_time" class="w-10/12">
					<el-date-picker v-model="data.addInfo.release_time" :disabled-date="disabledDate" type="date"
						:placeholder="$t('message.pleaseSelect')" format="YYYY/MM/DD" value-format="x"
						style="width: 100%;" />
				</el-form-item>
				<el-form-item :label="$t('goods.list.gift') + ':'" prop="is_gift" class="w-10/12">
					<el-radio-group v-model="data.addInfo.is_gift">
						<el-radio :value="1" :label="1">{{ $t('public.yes') }}</el-radio>
						<el-radio :value="2" :label="2">{{ $t('public.no') }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item :label="$t('machine.configs.recommendingGood') + ':'" prop="is_recommend" class="w-10/2">
					<el-radio-group v-model="data.addInfo.is_recommend">
						<el-radio :value="1" :label="1">{{ $t('public.yes') }}</el-radio>
						<el-radio :value="2" :label="2">{{ $t('public.no') }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item :label="$t('machine.channel.shelfWay') + ':'" prop="shelf_way" class="w-10/12">
					<el-select v-model="data.addInfo.shelf_way">
						<el-option :label="$t('machine.channel.ornament')" value="1" />
						<el-option :label="$t('machine.channel.Pendant')" value="2" />
						<el-option :label="$t('machine.channel.Grid')" value="3" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('order.consume.location') + ':'" prop="channel_position" class="w-10/12">
					<el-select v-model="data.addInfo.channel_position">
						<el-option :label="$t('order.consume.main')" value="1" />
						<el-option :label="$t('order.consume.auxiliary')" value="2" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('machine.channel.pick') + ':'" prop="fetch_mode" class="w-10/12">
					<el-select v-model="data.addInfo.fetch_mode">
						<el-option v-for="(item, key) in data.channel_type" :key="key" :label="item" :value="key" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('machine.channel.channelStatus') + ':'" prop="status" class="w-10/12">
					<el-select v-model="data.addInfo.status">
						<el-option v-for="(item, key) in data.channel_statsu" :key="key" :label="item" :value="key" />
					</el-select>
				</el-form-item>
			</el-form>
			<el-form-item :label="$t('goods.list.pack') + '(mm):'" prop="length" class="ml-4">
				<div id="goodsPack" class="w-full relative flex">
					<div class="mr-2">
						<el-input v-model="data.addInfo.length" disabled :placeholder="$t('message.pleaseEnter')">
							<template #append>
								{{ $t('goods.list.length') }}
							</template>
						</el-input>
					</div>
					X
					<div class=" ml-2 mr-2">
						<el-input v-model="data.addInfo.width2" disabled :placeholder="$t('message.pleaseEnter')">
							<template #append>
								{{ $t('goods.list.width') }}
							</template>
						</el-input>
					</div>
					X
					<div class="ml-2 mr-2">
						<el-input v-model="data.addInfo.height2" disabled :placeholder="$t('message.pleaseEnter')">
							<template #append>
								{{ $t('goods.list.height') }}
							</template>
						</el-input>
					</div>
				</div>
			</el-form-item>
			<div class="text-center">
				<el-button type="primary" @click="addSubmit()">{{ $t('public.save') }}</el-button>
				<el-button @click="addDialog = false">{{ $t('public.cancel') }}</el-button>
			</div>
		</el-dialog>
		<!-- 编辑货道 -->
		<el-dialog v-model="data.chstatus" :title="data.chinfo.g_name" center width="30%">
			<el-form v-if="data.chstatus" :model="data.chinfo" :inline="true"
				:label-width="language == 'en' ? '140' : '100'">
				<div class="relative w-10/12">
					<div class="absolute top-0 right-0 pb-4" style="max-width: 100px;max-height: 140px;">
						<div class="border">
							<img :src="data.chinfo.pic || product">
						</div>
					</div>
				</div>
				<el-form-item :label="$t('machine.channel.sellInve') + ':'" prop="stock" class="w-full">
					<el-input-number v-model="data.chinfo.stock" :min="0" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.channelCap') + ':'" prop="capacity" class="w-full">
					<el-input-number v-model="data.chinfo.capacity" :min="0" />
				</el-form-item>
				<el-form-item :label="$t('machine.goods.name') + ':'" prop="g_id" class="w-10/12">
					<el-select disabled v-model="data.chinfo.g_id" @change="changeGoods">
						<el-option v-for="(item, key) in goodsList" :key="key" :label="item.g_id + '-' + item.g_name"
							:value="item.g_id" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('machine.channel.priceProduct') + ':'" prop="retail_price" class="w-10/12">
					<el-input v-model="data.chinfo.retail_price" :placeholder="$t('message.pleaseEnter')"
						type="number" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.pick') + ':'" prop="fetch_mode" class="w-10/12">
					<el-select v-model="data.chinfo.fetch_mode">
						<el-option v-if="info.machine_level == 1" v-for="(item, key) in data.channel_type_level01"
							:key="key" :label="item" :value="key" />
						<el-option v-else v-for="(item, index) in data.channel_type" :key="index" :label="item"
							:value="index" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('machine.channel.channelStatus') + ':'" prop="status" class="w-10/12">
					<el-select v-model="data.chinfo.status">
						<el-option v-for="(item, key) in data.channel_statsu" :key="key" :label="item" :value="key" />
					</el-select>
				</el-form-item>
				<el-form-item label="SKU:" prop="sku" class="w-10/12">
					<el-input disabled v-model="data.chinfo.sku" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<el-form-item :label="$t('machine.channel.inventoryWarn') + ':'" prop="stock_warning" class="w-10/12">
					<el-input v-model.number="data.chinfo.stock_warning" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>
				<div class="w-full text-center">
					<div class="inline-block">
						<el-button type="primary" @click="submit()">{{ $t('public.save') }}</el-button>
						<el-button @click="data.chstatus = false">{{ $t('public.cancel') }}</el-button>
					</div>
				</div>
			</el-form>
		</el-dialog>

		<el-dialog v-model="data.macimgurl" center width="30%">
			<div v-loading="data.mtloading" class="flex justify-center">
				<el-image v-if="!data.mtloading" :src="data.imgurl"></el-image>
			</div>
		</el-dialog>
		<el-dialog v-model="data.dialogImage" :title="$t('machine.addMachine.material')" center width="30%">
			<div class="flex justify-center">
				<el-image class="max-w-80" v-if="data.file_path" :src="data.file_path" fit="fill" />
				<img class="max-w-80" v-else src="@/assets/unPic.png" fit="fill" />
			</div>
		</el-dialog>
		<exports :dialogVisible="dialogExport" @close="dialogExport = false" />
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import product from '@/assets/product.png';
import { getchannelList, getChannelImg, updatechannel, channelExport, exportSku, addchannel, delchannel } from '@/api/machine';
import { ElMessage, ElMessageBox } from "element-plus";
import exports from '@/components/export.vue';
import { getgoodsList } from '@/api/goods'
import { onMounted } from 'vue'
const { locale } = useI18n()
let language = ref()
onMounted(() => {
	language.value = locale.value
})
let addDialog = ref(false)
const dialogExport = ref(false)
let props = defineProps({
	info: {
		type: Object,
		default: {}
	},
	find: {
		type: Object,
		default: {}
	}
})
let data = reactive({
	file_path: '',
	dialogImage: false,
	macimgurl: false, // 弹窗
	mtloading: false, // 加载
	chstatus: false, // 修改货道弹窗
	imgurl: '', // 图片
	list: [], // 列表信息
	mactype: 1, // 机组类型
	types: 1, // 查看类型
	channel_type: [ // 取货模式
		$t('machine.configs.default'),
		$t('machine.configs.Upper'),
		$t('machine.configs.Lower'),
		$t('machine.configs.Convenient'),
		$t('machine.configs.Heavy'),
		$t('machine.configs.Instant'),
		$t('machine.configs.Flat'),
		$t('machine.extrapolation'),
		$t('machine.suspension'),
		$t('machine.telescopicStrap')
	],
	channel_type_level01: [ // 取货模式
		$t('machine.configs.default'),
		$t('machine.extrapolation'),
		$t('machine.suspension'),
		$t('machine.telescopicStrap')
	],
	channel_statsu: [ // 货道状态
		$t('public.normal'),
		$t('public.disable'),
		'BAD'
	],
	chinfo: {}, // 货道信息
	addInfo: {
		channel_code: '',
		g_id: '',
		bar_code: '',
		batch_number: '',
		length: '',
		width2: '',
		height2: '',
		slot_hole: '',
		capacity: '',
		stock: '',
		stock_warning: '',
		release_time: '',
		is_gift: '',
		is_recommend: '',
		shelf_way: '',
		channel_position: '',
		fetch_mode: '',
		status: '',
		pic: '',
		g_name: '',
		gc_id: '',
		gc_name: '',
		sku: ''
	}, // 添加货道信息
	rules: {
		channel_code: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		g_id: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
	}
})
const changeGoods = (val:number)=>{
	goodsList.value.forEach(item => {
		if(val==item.g_id){
			data.chinfo.retail_price = item.retail_price
			data.chinfo.sku = item.sku || item.sku2
			data.chinfo.pic = item.pic
		}
	})
}
const delChannel = (row: any) => {
	ElMessageBox.confirm($t('message.delData'))
		.then(res => {
			delchannel({ mc_id: row.mc_id }).then(res => {
				if (res.state == 200) {
					ElMessage({
						message: $t('message.delSuccess'),
						type: 'success'
					})
					getlist()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}).catch(err => {
			console.log('取消')
		})
}
const mouseleave = (row) => {
	row.isChannelinfo = false
}
const mousedown = (row) => {
	row.isChannelinfo = true
}
// 查看素材
let urlimg = (e) => {
	data.dialogImage = true;
	data.file_path = e;
}
let addChannel = () => {
	data.addInfo = {}
	addDialog.value = true
}
const goodsList = ref([])
let visibleGoods = () => {
	getgoodsList({}).then(res => {
		if (res.state == 200) {
			goodsList.value = res.data
		}
	})
}
visibleGoods()
// 获取列表信息
let getlist = () => {
	data.list = []
	getchannelList({ m_id: props.info.m_id }).then(res => {
		if (res.state == 200) {
			res.data.sort(getSortFun('asc'))

			data.list = groupedItems(res.data)
		}
	})
}

// 取货方式
let getmode = (e) => {
	if (props.info.machine_level == 1) {
		return data.channel_type_level01[e - 1]
	} else {
		return data.channel_type[e - 1]
	}
}

// 拍摄货道照片
let capture = (e) => {
	let channel_img = {
		machine_id: props.info.machine_id,
		channel_code: e
	}
	data.macimgurl = true
	data.mtloading = true
	getChannelImg(channel_img).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			data.imgurl = res.data
		}
	}).catch(err => {
		data.mtloading = false
	})
}
let goodsChange = (val: number) => {
	let arr = goodsList.value.filter(item => item.g_id == val)
	data.addInfo.g_name = arr[0].g_name
	data.addInfo.gc_id = arr[0].gc_id
	data.addInfo.gc_name = arr[0].gc_name
	data.addInfo.pic = arr[0].pic
	data.addInfo.sku = arr[0].sku
	data.addInfo.length = arr[0].length
	data.addInfo.width2 = arr[0].width
	data.addInfo.height2 = arr[0].height
}
// 货道信息弹窗
let channel_info = (e) => {
	data.chstatus = true
	data.chinfo = {
		mc_id: e.mc_id,
		g_name: e.g_name || '',
		stock: e.stock || 0,
		capacity: e.capacity || 0,
		retail_price: e.retail_price || 0,
		fetch_mode: e.fetch_mode - 1 || 0,
		sku: e.sku || '',
		pic: e.pic || '',
		status: e.status - 1 || 0,
		stock_warning: e.stock_warning,
		g_id: e.g_id || ''
	}
}
let addSubmit = () => {
	data.addInfo.channel_code = data.addInfo.channel_code.toUpperCase()
	data.addInfo.release_time = Math.floor(data.addInfo.release_time / 1000)
	data.addInfo.m_id = props.info.m_id
	data.addInfo.machine_id = props.info.machine_id
	addchannel(data.addInfo).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.addSuccess'),
				type: 'success'
			})
			addDialog.value = false
			getlist()
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}

let submit = () => {
	if (data.chinfo.stock > data.chinfo.capacity) {
		ElMessage({
			message: $t('message.quantityNum'),
			type: 'error'
		})
		return
	}
	let obj = {
		mc_id: data.chinfo.mc_id,
		stock: data.chinfo.stock,
		capacity: data.chinfo.capacity,
		fetch_mode: data.chinfo.fetch_mode + 1,
		sku: data.chinfo.sku,
		status: data.chinfo.status + 1,
		stock_warning: data.chinfo.stock_warning,
		retail_price: data.chinfo.retail_price,
		g_id: data.chinfo.g_id
	}
	updatechannel(obj).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.modifySuccess'),
				type: 'success'
			})
			data.chstatus = false
			getlist()
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}
// 按首字母排序
let getSortFun = (order) => {
	let ordAlpah = (order == 'asc') ? '>' : '<';
	var sortFun = new Function('a', 'b', 'return a.channel_code' + ordAlpah + 'b.channel_code' + '?1:-1');
	return sortFun
}

// 按首字母分组
let groupedItems = (items) => {
	let grouped = {};
	for (let item of items) {
		let firstLetter = item.channel_code[0].toUpperCase()
		if (!grouped[firstLetter]) {
			grouped[firstLetter] = [];
		}

		item.custom = (item.width2)
		if (item.custom == 0) {
			item.custom = 100
		}

		grouped[firstLetter].push(item);
	}
	return grouped;
}

// 导出
let getExport = (type) => {
	let obj = {
		m_id: props.info.m_id
	}
	ElMessageBox.confirm($t('message.isExport')).then(res => {
		if (type == 1) {
			channelExport(obj).then(res => {
				if (res.state == 200) {
					dialogExport.value = true
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			}).catch(err => {
				console.log(err)
			})
		}
		if (type == 2) {
			exportSku(obj).then(res => {
				if (res.state == 200) {
					dialogExport.value = true
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			}).catch(err => {
				console.log(err)
			})
		}
	}).catch(err => {
		console.log('取消')
	})
}

getlist()

</script>
<style lang="scss" scoped>
.delChannel {
	.el-button+.el-button {
		margin-left: 0px;
		margin-bottom: 20px;
	}

	.el-button {
		margin-bottom: 10px;
	}
}
</style>
